import React, { useState } from 'react';
import { Card, Modal, Row, Select, Button } from 'antd';

import Transfer from '@/components/Transfer';
import { maxLength } from '@/utils/form';
import { REGION_ADDRESS_TYPE } from '@/Constants';
import api from '@/api';

const Option = Select.Option;
export default class Pop extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      countries: [],
      selectedCountry: '',
      selectedArea1: '',
      selectedArea2: '',
      selectedArea3: '',
      areas1: [],
      areas2: [],
      areas3: [],
      areas4: [],
      selectedItems: [],
      regionItems: [],
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.modalVisible) {
      this.searchCountries();
      let selectedItems = nextProps.selectedItems;
      this.setState({
        selectedItems,
        regionItems: nextProps.regionItems,
        selectedCountry: '',
        selectedArea1: '',
        selectedArea2: '',
        selectedArea3: '',
      });
    }
  }

  searchCountries = () => {
    const { regionAddressType } = this.props;
    api.cooperativeStore
      .queryCountries({
        queryParams: {
          pageSize: 300,
        },
      })
      .then(res => {
        if (res.code === 200) {
          let countries = res.data.map(item => ({ ...item, name: `${item.name}(${item.code})` }));
          if (regionAddressType === REGION_ADDRESS_TYPE.AIR_PORT) {
            this.setState({
              countries,
              dataSource: [],
            });
          } else if (regionAddressType === REGION_ADDRESS_TYPE.AREA) {
            this.setState({
              countries,
              dataSource: countries,
            });
          }
        }
      });
  };

  handleCountryChange = value => {
    const { regionAddressType } = this.props;
    if (regionAddressType === REGION_ADDRESS_TYPE.AREA) {
      api.cooperativeStore
        .queryAreas({
          queryParams: {
            parentId: 0,
            countryCode: value,
            pageSize: 300,
          },
        })
        .then(res => {
          if (res.errorCode === 0) {
            let areas1 = res.data;
            this.setState({
              areas1,
              selectedCountry: value,
              dataSource: areas1,
              selectedArea1: '',
              selectedArea2: '',
              selectedArea3: '',
            });
          }
        });
    } else if (regionAddressType === REGION_ADDRESS_TYPE.AIR_PORT) {
      api.cooperativeStore
        .queryCities({
          queryParams: {
            countryCode: value,
            pageSize: 300,
          },
        })
        .then(res => {
          if (res.errorCode === 0) {
            let areas1 = res.data;
            this.setState({
              areas1,
              selectedCountry: value,
              selectedArea1: '',
              selectedArea2: '',
              selectedArea3: '',
            });
          }
        });
      api.cooperativeStore
        .queryPorts({
          queryParams: {
            countryCode: value,
            pageSize: 300,
          },
        })
        .then(res => {
          if (res.errorCode === 0) {
            this.setState({
              dataSource: res.data,
            });
          }
        });
    }
  };

  handleArea1Change = value => {
    const { regionAddressType } = this.props;
    const { selectedCountry } = this.state;
    if (regionAddressType === REGION_ADDRESS_TYPE.AREA) {
      return this.handleAreaChange(value, 1);
    }
    if (regionAddressType === REGION_ADDRESS_TYPE.AIR_PORT) {
      return api.base.queryPorts({
        countryCode: selectedCountry,
        cityCode: value,
        pageSize: 300,
      }).then(res => {
        if (res.errorCode === 0) {
          this.setState({
            dataSource: res.data,
            selectedArea1: value,
          });
        }
      });
    }
  };

  handleAreaChange = (value, level) => {
    const { selectedCountry } = this.state;
    api.base
      .queryAreas({
        queryParams: {
          parentId: value,
          countryCode: selectedCountry,
          pageSize: 300,
        },
      })
      .then(res => {
        if (res.errorCode === 0) {
          let areas = res.data;
          let resetState = {};
          for (let i = level + 1; i <= 3; i++) {
            resetState[`selectedArea${i}`] = '';
          }
          this.setState({
            ...resetState,
            [`areas${level + 1}`]: areas,
            [`selectedArea${level}`]: value,
            dataSource: areas,
          });
        }
      });
  };

  handleSearchArea = (value, level) => {
    const { selectedCountry, selectedArea1, selectedArea2, selectedArea3 } = this.state;
    let parentId = '';
    switch (level) {
      case 1:
        parentId = 0;
        break;
      case 2:
        parentId = selectedArea1;
        break;
      case 3:
        parentId = selectedArea2;
        break;
      case 4:
        parentId = selectedArea3;
        break;
      default:
        parentId = 0;
        break;
    }
    api.base
      .queryAreas({
        queryParams: {
          q: value,
          parentId,
          countryCode: selectedCountry,
          pageSize: 300,
        },
      })
      .then(res => {
        if (res.errorCode === 0) {
          let areas = res.data;
          let resetState = {};
          for (let i = level + 1; i <= 3; i++) {
            resetState[`selectedArea${i}`] = '';
          }
          this.setState({
            [`areas${level + 1}`]: areas,
            dataSource: areas,
            ...resetState,
          });
        }
      });
  };

  handleChange = (targetItems, direction, moveItems) => {
    const {
      regionItems,
    } = this.state;

    let newItems = this.transformRegionItem(moveItems);
    let newRegions = [...regionItems];
    if (direction === 'right') {
      newRegions.push(...newItems);
    } else {
      newRegions = newRegions.filter(
        items => !moveItems.some(m => m.code === items[items.length - 1].code)
      );
    }

    this.setState({
      selectedItems: targetItems,
      regionItems: newRegions,
    });
  };

  transformRegionItem = moveItems => {
    const { selectedCountry, selectedArea1, selectedArea2, selectedArea3 } = this.state;
    let newItems = moveItems.map(item => [item]);
    if (selectedArea3) {
      newItems = newItems.map(item => [{ code: selectedArea3 }, ...item]);
    }
    if (selectedArea2) {
      newItems = newItems.map(item => [{ code: selectedArea2 }, ...item]);
    }
    if (selectedArea1) {
      newItems = newItems.map(item => [{ code: selectedArea1 }, ...item]);
    }
    if (selectedCountry) {
      newItems = newItems.map(item => [{ code: selectedCountry }, ...item]);
    }
    return newItems;
  };

  handleSearch = (direction, value) => {
    const { regionAddressType } = this.props;
    const { selectedCountry, selectedArea1, selectedArea2, selectedArea3 } = this.state;
    let level = 0;
    if (selectedCountry) level = 1;
    if (selectedArea1) level = 2;
    if (selectedArea2) level = 3;
    if (selectedArea3) level = 4;

    if (
      direction === 'left' &&
      selectedCountry &&
      regionAddressType !== REGION_ADDRESS_TYPE.AIR_PORT
    ) {
      this.handleSearchArea(value, level);
    }
  };

  handleReset = () => {
    this.setState({
      selectedCountry: '',
      selectedArea1: '',
      selectedArea2: '',
      selectedArea3: '',
    });
    this.searchCountries();
  };

  showItem = item => {
    const { regionAddressType } = this.props;
    if (regionAddressType === REGION_ADDRESS_TYPE.AREA) {
      return item.name;
    }
    if (regionAddressType === REGION_ADDRESS_TYPE.AIR_PORT) {
      return `${item.name}(${item.code})`;
    }
  };
  render(){
    const { modalVisible, handleModalVisible, handleSave, regionAddressType } = this.props;
    const {
      dataSource,
      countries,
      areas1,
      areas2,
      areas3,
      selectedCountry,
      selectedArea1,
      selectedArea2,
      selectedArea3,
      selectedItems,
      regionItems,
    } = this.state;

    const okHandle = () => {
      handleSave(selectedItems, regionItems);
      handleModalVisible();
    };
    return (
          <div>
              <Modal
                  maskClosable={false}
                  keyboard={false}
                  destroyOnClose
                  title="添加区域"
                  visible={modalVisible}
                  onOk={okHandle}
                  width={1000}
                  onCancel={() => handleModalVisible()}
                >
                  <Row type="flex">
                    <Card bodyStyle={{ width: 280 }} style={{ marginRight: 45 }}>
                      <p>首先在本栏选择分区所在范围，然后在待选区查看并选择。</p>
                      <Select
                        showSearch
                        optionFilterProp="children"
                        value={selectedCountry}
                        onChange={this.handleCountryChange}
                        onInputKeyDown={e => maxLength(e, 30)}
                        style={{ width: '100%' }}
                        filterOption={(inputValue, option) => {
                          let val = inputValue.trim();
                          return option.props.children.includes(val.toUpperCase());
                        }}
                      >
                        {countries.map(val => (
                          <Option key={val.code} value={val.code}>{`${val.name}`}</Option>
                        ))}
                      </Select>
                      {regionAddressType === REGION_ADDRESS_TYPE.AREA && (
                        <>
                          <Select
                            showSearch
                            optionFilterProp="children"
                            onChange={this.handleArea1Change}
                            onInputKeyDown={e => maxLength(e, 30)}
                            style={{ width: '100%', marginTop: 15 }}
                            value={selectedArea1}
                            disabled={!selectedCountry || selectedCountry !== 'CN'}
                            filterOption={(inputValue, option) => {
                              let val = inputValue.trim();
                              return option.props.children.includes(val.toUpperCase());
                            }}
                          >
                            {areas1.map(val => (
                              <Option key={val.code} value={val.code}>
                                {val.name}
                              </Option>
                            ))}
                          </Select>
                          <Select
                            showSearch
                            optionFilterProp="children"
                            onChange={value => this.handleAreaChange(value, 2)}
                            onInputKeyDown={e => maxLength(e, 30)}
                            style={{ width: '100%', marginTop: 15 }}
                            value={selectedArea2}
                            disabled={!selectedArea1 || selectedCountry !== 'CN'}
                            filterOption={(inputValue, option) => {
                              let val = inputValue.trim();
                              return option.props.children.includes(val.toUpperCase());
                            }}
                          >
                            {areas2.map(val => (
                              <Option key={val.code} value={val.code}>
                                {val.name}
                              </Option>
                            ))}
                          </Select>
                          <Select
                            showSearch
                            optionFilterProp="children"
                            onChange={value => this.handleAreaChange(value, 3)}
                            onInputKeyDown={e => maxLength(e, 30)}
                            style={{ width: '100%', marginTop: 15 }}
                            value={selectedArea3}
                            disabled={!selectedArea2 || selectedCountry !== 'CN'}
                            filterOption={(inputValue, option) => {
                              let val = inputValue.trim();
                              return option.props.children.includes(val.toUpperCase());
                            }}
                          >
                            {areas3.map(val => (
                              <Option key={val.code} value={val.code}>
                                {val.name}
                              </Option>
                            ))}
                          </Select>
                        </>
                      )}
                      <Button
                        type="primary"
                        onClick={this.handleReset}
                        style={{ marginTop: 10, float: 'right' }}
                      >
                        重置
                      </Button>
                    </Card>
                    <Transfer
                      listStyle={{
                        width: 280,
                        height: 672,
                      }}
                      rowKey={record => record.code}
                      titles={['待选地区', '已选地区']}
                      dataSource={dataSource}
                      showSearch
                      filterOption={(inputValue, option) => {
                        let values = inputValue
                          .trim()
                          .split(/[\s+,，;\t]+/)
                          .filter(Boolean);
                        return values.some(val => `${option.name}${option.code}`.includes(val.toUpperCase()));
                      }}
                      targetItems={selectedItems}
                      onChange={this.handleChange}
                      onSelectChange={this.handleSelectChange}
                      onSearch={this.handleSearch}
                      render={this.showItem}
                    />
                  </Row>
                </Modal>
          </div>
      );
  }
}

